<?php
require_once('data/SugarBean.php');
require_once('include/nusoap/nusoap.php');
require_once('include/nusoap/class.wsdlcache.php');
require_once('include/SugarPHPMailer.php');
//require_once('include/nusoap/class.wsdl.php');

class R2Connector {
	var $user_update_fields = array();
	var $contact_update_fields = array();
	var $soapclient;
		
	function UpdateR2BeforeSave(&$bean, $event, $arguments)
	{
		
	}
	
	function UpdateR2AfterSave(&$bean, $event, $arguments)
	{
		global $app_list_strings;
		$this->compile_update_arrays($bean);
		if(empty($bean->fetched_row['id'])){
			$session = $this->r2_login();

			//Create new user
			$params = array(	'session'=>$session,
								'module_name'=>'Users',
								'name_value_list' =>$this->user_update_fields
							);
			$create_result = $this->soapclient->call('set_entry', $params);
			$this->log_SOAP_result($create_result, $params);
			 
			 //Create new contact
			$params = array(	'session'=>$session,
								'module_name'=>'Contacts',
								'name_value_list' =>$this->contact_update_fields
							);
			$create_result = $this->soapclient->call('set_entry', $params);
			$this->log_SOAP_result($create_result, $params);
		}else{
			if(sizeof($this->user_update_fields) > 0){
				//Update existing user
				$session = $this->r2_login();

				array_push($this->user_update_fields, array('name'=>'id', 'value'=>$bean->id));
				$params = array(	'session'=>$session,
									'module_name'=>'Users',
									'name_value_list' => $this->user_update_fields
						);
				$update_result = $this->soapclient->call('set_entry', $params);
				$this->log_SOAP_result($update_result, $params);
			}
			if(sizeof($this->contact_update_fields) > 0){
				//Update existing contact
				if(is_null($session)){
					$session = $this->r2_login();
				}
				$params = array(	'session'=>$session,
									'module_name'=>'Contacts',
									'query'=>'(contacts.first_name=\''.$bean->fetched_row['first_name'].'\' AND contacts.last_name=\''.$bean->fetched_row['last_name'].'\')',
									'order_by'=>'',
									'offset'=>0,
									'select_fields'=>array('id'),
									'max_results'=>10,
									'deleted'=>-1
								);
				$contact_list = $this->soapclient->call('get_entry_list', $params);
				$this->log_SOAP_result($contact_list, $params);
				$id_field = array(array('name'=>'id', 'value'=>$contact_list['entry_list'][0]['id']));
				$params = array(	'session'=>$session,
									'module_name'=>'Contacts',
									'name_value_list' => array_merge($id_field, $this->contact_update_fields)
								);
				$update_result = $this->soapclient->call('set_entry', $params);
				$this->log_SOAP_result($update_result, $params);
			}
		}
	}
	
	function compile_update_arrays($bean){
		if($bean->fetched_row['first_name'] != $bean->first_name){
			// if(empty($bean->first_name)){$bean->first_name = "";}
			array_push($this->user_update_fields, array('name'=>'first_name', 'value'=>(string)$bean->first_name));
			array_push($this->contact_update_fields, array('name'=>'first_name', 'value'=>(string)$bean->first_name));
		}
		if($bean->fetched_row['last_name'] != $bean->last_name){
			array_push($this->user_update_fields, array('name'=>'last_name', 'value'=>(string)$bean->last_name));
			array_push($this->contact_update_fields, array('name'=>'last_name', 'value'=>(string)$bean->last_name));
		}
		if($bean->emailAddress->getPrimaryAddress($bean) != $bean->email1){
			array_push($this->user_update_fields, array('name'=>'email1', 'value'=>(string)$bean->email1));
			array_push($this->contact_update_fields, array('name'=>'email1', 'value'=>(string)$bean->email1));
		}
		if($bean->fetched_row['phone_mobile'] != $bean->phone_mobile){
			array_push($this->user_update_fields, array('name'=>'phone_mobile', 'value'=>(string)$bean->phone_mobile));
		}
		if($bean->fetched_row['phone_work'] != $bean->phone_work){
			array_push($this->user_update_fields, array('name'=>'phone_work', 'value'=>(string)$bean->phone_work));
		}
		if($bean->fetched_row['status'] != $bean->status){
			array_push($this->user_update_fields, array('name'=>'status', 'value'=>(string)$bean->status));
		}
		if($bean->fetched_row['address_street'] != $bean->address_street || $bean->fetched_row['address_city'] != $bean->address_city){
			array_push($this->user_update_fields, array('name'=>'address_street', 'value'=>(string)$bean->address_street.', '.(string)$bean->address_city));
		}
		if($bean->fetched_row['address_state'] != $bean->address_state){
			array_push($this->user_update_fields, array('name'=>'address_state', 'value'=>(string)$bean->address_state));
		}
		if($bean->fetched_row['address_country'] != $bean->address_country){
			array_push($this->user_update_fields, array('name'=>'address_country', 'value'=>(string)$bean->address_country));
		}
		if($bean->fetched_row['address_postalcode'] != $bean->address_postalcode){
			array_push($this->user_update_fields, array('name'=>'address_postalcode', 'value'=>(string)$bean->address_postalcode));
		}
		if($bean->fetched_row['employee_status'] != $bean->employee_status){
			array_push($this->user_update_fields, array('name'=>'employee_status', 'value'=>(string)$bean->employee_status));
		}
		if($bean->fetched_row['messenger_id'] != $bean->messenger_id){
			array_push($this->user_update_fields, array('name'=>'messenger_id', 'value'=>(string)$bean->messenger_id));
		}
		if(	$bean->fetched_row['bank_account_name'] != $bean->bank_account_name ||
			$bean->fetched_row['branch_name'] != $bean->branch_name ||
			$bean->fetched_row['bank_name'] != $bean->bank_name ||
			$bean->fetched_row['branch_address'] != $bean->branch_address ||
			$bean->fetched_row['branch_city'] != $bean->branch_city ||
			$bean->fetched_row['branch_state'] != $bean->branch_state ||
			$bean->fetched_row['branch_postalcode'] != $bean->branch_postalcode ||
			$bean->fetched_row['intermediary_bank_account_name'] != $bean->intermediary_bank_account_name ||
			$bean->fetched_row['intermediary_bank_name'] != $bean->intermediary_bank_name ||
			$bean->fetched_row['intermediary_bank_account_number'] != $bean->intermediary_bank_account_number ||
			$bean->fetched_row['intermediary_bank_info_note'] != $bean->intermediary_bank_info_note
		){
			$descriptionField = $bean->bank_account_name.PHP_EOL.
								($bean->bank_name != '' ? 'Bank Name: '.$bean->bank_name.PHP_EOL : '').
								($bean->branch_name != '' ? 'Branch Name: '.$bean->branch_name.PHP_EOL : '').
								$bean->branch_address.
								($bean->branch_city != '' ? ', '.$bean->branch_city: '').
								($bean->branch_state != '' ? ', '.$bean->branch_state: '').
								($bean->branch_postalcode != '' ? ', '.$bean->branch_postalcode: '').
								PHP_EOL.PHP_EOL.
								$bean->intermediary_bank_account_name.PHP_EOL.
								($bean->intermediary_bank_name != '' ? 'Intermediary Bank Name: '.$bean->intermediary_bank_name.PHP_EOL : '').
								($bean->intermediary_bank_account_number != '' ? 'Account #: '.$bean->intermediary_bank_account_number.PHP_EOL : '').
								$bean->intermediary_bank_info_note;
			array_push($this->user_update_fields, array('name'=>'description', 'value'=>trim($descriptionField)));
		}
		if($bean->fetched_row['bank_account_number'] != $bean->bank_account_number){
			array_push($this->user_update_fields, array('name'=>'phone_other', 'value'=>(string)$bean->bank_account_number));
		}
		if($bean->fetched_row['branch_code'] != $bean->branch_code){
			array_push($this->user_update_fields, array('name'=>'address_city', 'value'=>(string)$bean->branch_code));
		}
		if($bean->fetched_row['iban_number'] != $bean->iban_number){
			array_push($this->user_update_fields, array('name'=>'phone_home', 'value'=>(string)$bean->iban_number));
		}
		if($bean->fetched_row['swift_code'] != $bean->swift_code){
			array_push($this->user_update_fields, array('name'=>'phone_fax', 'value'=>(string)$bean->swift_code));
		}
		
		if(empty($bean->fetched_row['id'])){
			$query = "SELECT editor_number FROM users WHERE id='{$bean->id}'";

			$result = $bean->db->query($query);
			$row = $bean->db->fetchByAssoc($result);
			
			$editor_number = str_pad($row['editor_number'], 3, '0', STR_PAD_LEFT);
			$editor_code = ($bean->banking_country == '' ? 'xx' : $bean->banking_country).$editor_number;
			array_push($this->user_update_fields, array('name'=>'title', 'value'=>$editor_code));
			array_push($this->user_update_fields, array('name'=>'user_name', 'value'=>strtolower(substr($bean->first_name, 0, 1).$bean->last_name.$editor_number)));
			array_push($this->user_update_fields, array('name'=>'id', 'value'=>$bean->id));
			array_push($this->user_update_fields, array('name'=>'new_with_id', 'value'=>1));
			array_push($this->user_update_fields, array('name'=>'status', 'value'=>'Inactive'));
			array_push($this->user_update_fields, array('name'=>'receive_notifications', 'value'=>0));
			
			array_push($this->contact_update_fields, array('name'=>'contact_type1_c', 'value'=>'editor'));
			
		}else{
			if($bean->fetched_row['banking_country'] != $bean->banking_country){
				array_push($this->user_update_fields, array('name'=>'title', 'value'=>$bean->banking_country.str_pad($bean->editor_number, 3, '0', STR_PAD_LEFT)));
			}
		}
	}
	
	function r2_login(){
		global $sugar_config;
		if(is_null($this->soapclient)){
			$cache = new wsdlcache('cache/wsdlcache/', 86400);
			$wsdl = $cache->get($sugar_config['r2_connector_config']['r2_soap_url']);
			if(is_null($wsdl)) {
				$wsdl = new wsdl($sugar_config['r2_connector_config']['r2_soap_url']);
				$cache->put($wsdl);
			}
	
			//$r2_soap_url = $sugar_config['r2_connector_config']['r2_soap_url'];
			//$this->soapclient = new nusoapclient($r2_soap_url, true);
			$this->soapclient = new nusoapclient($wsdl, true);
//				$GLOBALS['log']->fatal("CONNECT | soapclient: = ".print_r($this->soapclient, true));
		}
		
		$user_name= $sugar_config['r2_connector_config']['user_name'];
		$user_password= $sugar_config['r2_connector_config']['user_password'];
		$application_name = 'SoapTest';
		$params = array(	'user_auth' => array(	'user_name'=>$user_name,
													'password'=>md5($user_password),
													'version'=>'1.0'
												),
							'application_name'=>$application_name
						);
		$result = $this->soapclient->call('login', $params);

		$this->log_SOAP_result($result, $params);
		return $result['id'];
	}

	function log_SOAP_result($result, $params){
		
		if($result['error']['number'] != 0){
	//  	mail('zanghongwen@edanzgroup.com', 'SOAP failure | '.$result['error']['name'], $result['error']['description']."\nResponse: ".print_r($result, true)."\nParameters: ".print_r($params, true));
			$email = new SugarPHPMailer();
			$email->AddAddress('zanghongwen@edanzgroup.com');
			//$email->IsHTML(true);
			$email->Body = $result['error']['description']."\nResponse: ".print_r($result, true)."\nParameters: ".print_r($params, true);
			$email->Subject = "SOAP failure from S2 --".$result['error']['name'];
			$email->From = "zanghongwen@edanzgroup.com";
			$email->FromName = "S2";
			$email->prepForOutbound();
			$email->setMailerForSystem();
			$email->Send();
			$GLOBALS['log']->fatal('SOAP failure | '.$result['error']['name']."\nResponse: ".print_r($result, true)."\nParameters: ".print_r($params, true)."\n".$this->soapclient->response);
		}
		else{
			//$GLOBALS['log']->fatal('SOAP success '.$this->soapclient->response);
			$GLOBALS['log']->fatal('SOAP success');
		}
	}
}

?>
